/*
 * @Author: moeWang
 * @Date: 2022-03-07 14:35:05
 * @LastEditTime: 2022-03-08 14:59:39
 * @LastEditors: moeWang
 * @Description:
 * @FilePath: \nest-web\src\logical\role\service\role.service.ts
 */

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { RpAccount } from 'src/logical/account/entity/account.entity';
import { RpAccountViewModel } from 'src/logical/account/models/accountView.model';
import { AccountService } from 'src/logical/account/service/account.service';
import { BaseListResultModel } from 'src/logical/common/models/BaseListResult.model';
import { BaseResultModel } from 'src/logical/common/models/BaseResult.model';
import { Pagination } from 'src/logical/common/models/Pagination.model';
import { BaseService } from 'src/logical/common/services/base.service';
import { MenuEntity } from 'src/logical/menu/entity/menu.entity';
import {
  RoleAccountEntity,
  RoleEntity,
  RoleMenuEntity,
} from '../entity/role.entity';
import { RoleModel } from '../model/role.model';

@Injectable()
export class RoleService extends BaseService {
  constructor(
    @InjectModel(RoleEntity)
    private roleEntity: typeof RoleEntity,
    private accountService: AccountService,
  ) {
    super();
  }

  async findAllByRoleId(id) {
    return await this.roleEntity.findOne({
      where: { roleId: id },
      include: [
        {
          model: MenuEntity,
        },
        {
          model: RpAccount,
          attributes: {
            include: ['createDate'],
            exclude: ['passwd'],
          },
        },
      ],

      // raw: true,
    });
  }

  async deleteById(id) {
    return await RoleEntity.destroy({
      where: { roleId: id },
    });
  }

  async findRoleIdByAccountId(accountId) {
    return await RoleAccountEntity.findAll({
      where: {
        accountId,
      },
    });
  }

  async save(roleModel: RoleModel): Promise<BaseResultModel<any>> {
    const roleEntity = new RoleEntity();
    const menus = [];
    const accounts = [];
    roleEntity.roleId = roleModel.roleId;
    roleEntity.roleName = roleModel.roleName;
    roleEntity.description = roleModel.description;
    for (let i = 0; i < roleModel.menuList.length; i++) {
      const t = roleModel.menuList[i];
      const menuEntity = new MenuEntity();
      menuEntity.menuId = t;
      menus.push(t);
    }
    for (let i = 0; i < roleModel.accountList.length; i++) {
      const t = roleModel.accountList[i];
      const accountEntity = new RpAccount();
      const optional = this.accountService.findById(t);
      // TODO: 判断账号是否激活
      accountEntity.id = t;
      accounts.push(t);
    }

    console.log(roleEntity.get());
    const res = await RoleEntity.upsert(roleEntity.get());
    console.log(res[0]);
    try {
      await res[0].$set('menus', menus, {
        through: 'rp_role_menu',
      });
      await res[0].$set('accounts', accounts, {
        through: 'rp_role_account',
      });
      return this.saveSuccessResultData();
    } catch (error) {
      console.log(error);
      RoleEntity.destroy({
        where: {
          roleId: res[0].get('roleId'),
        },
      });
      return this.saveFailedResultData('保存失败');
    }
  }

  async queryForList(
    queryModel,
    pagination,
  ): Promise<BaseListResultModel<Array<RoleModel>>> {
    let resList: Array<RoleModel> = new Array();
    let totalCount: number = 0;
    const pag = new Pagination();

    pag.setCurrent(pagination.current);
    pag.setPagesize(pagination.pagesize);
    pag.setTotal(pagination.total);

    resList = await this.roleEntity.findAll({
      where: queryModel,
      offset: pag.getCurrent() - 1,
      limit: pag.getPagesize(),
      // include: [
      //   {
      //     model: MenuEntity,
      //   },
      //   {
      //     model: RpAccount,
      //   },
      // ],
    });

    return this.querySuccessResultListData(resList, pag);
  }

  async detail(id): Promise<BaseResultModel<RoleModel>> {
    const rs = new RoleModel();

    const roleEntity = await this.findAllByRoleId(id);

    const roleMenuList = roleEntity.menus.map((item) => {
      return item.get('menuId');
    });
    const roleAccountList = roleEntity.accounts.map((item) => {
      return item.get('id');
    });
    const roleAccountDetailList = roleEntity.accounts.map((item) => {
      return item.get();
    });

    rs.roleId = roleEntity.roleId;
    rs.roleName = roleEntity.roleName;
    rs.menuList = roleMenuList;
    rs.accountList = roleAccountList;
    rs.accountDetailList = roleAccountDetailList;

    return this.resultData(rs, 200, '');
  }

  async delete(id): Promise<BaseResultModel<Object>> {
    try {
      const rs = await this.deleteById(id);
      return this.deleteSuccessResultData();
    } catch (error) {
      return this.deleteFailedResultData('删除失败');
    }
  }
}
